﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Linq;

namespace Nuctech.ACCT.OIS.SqlSugar.Client
{
    public static class SqlSugarExtensions
    {
        #region 公共方法

        public static void AddSqlSugarClient(this IServiceCollection service, DbSettingOption[]? dbSettingOptions)
        {
            var configs = dbSettingOptions
                ?.Where(x => x.IsEable == true)
                .Select(s => s.Connects)
                .ToList();

            var connectionConfigs = configs?.Select(x => new ConnectionConfig
            {
                ConfigId = x.ConfigId,
                ConnectionString = x.ConnectionString,
                DbType = x.DbType,
                IsAutoCloseConnection = x.IsAutoCloseConnection,
                InitKeyType = InitKeyType.Attribute,
                MoreSettings = GetMoreSeetings(x.DbType),
            }).ToList();

            _ = service.AddTransient<ISqlSugarClient>(s =>
            {
                var db = new SqlSugarClient(connectionConfigs,
                it =>
                {
                    foreach (var config in connectionConfigs)
                    {
                        it.GetConnection(config.ConfigId).Aop.OnLogExecuting = (sql, para) =>
                        {
                            Console.WriteLine($"{config.ConfigId}：" + UtilMethods.GetNativeSql(sql, para));
                        };
                    }
                });

                return db;
            });
        }

        #endregion


        #region 私有方法

        private static ConnMoreSettings GetMoreSeetings(DbType dbType)
        {
            ConnMoreSettings connMoreSettings = dbType switch
            {
                DbType.PostgreSQL => new ConnMoreSettings()
                {
                    PgSqlIsAutoToLower = false,
                    PgSqlIsAutoToLowerCodeFirst = false,
                },
                DbType.Kdbndp => new ConnMoreSettings()
                {
                    DatabaseModel = DbType.PostgreSQL,// 兼容系统表差异
                    IsAutoToUpper = false,
                },
                DbType.Dm => new ConnMoreSettings()
                {
                    IsAutoToUpper = false,
                },
                _ => new ConnMoreSettings()
            };

            return connMoreSettings;
        }

        #endregion

    }
}
